package com.sgb.kjwl.view.ui.activity.material;

import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.ImageView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityConcreteDetailBinding;
import com.sgb.kjwl.di.material.DaggerMaterialComponent;
import com.sgb.kjwl.di.material.MaterialModule;
import com.sgb.kjwl.model.entity.AdmixtureEntity;
import com.sgb.kjwl.model.entity.ConcreteDetailEntity;
import com.sgb.kjwl.model.entity.ConcreteFilterEntity;
import com.sgb.kjwl.model.entity.ConcreteParamEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.event.CustomViewsInfo;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.adapter.material.ConcreteAdmixAdapter;
import com.sgb.kjwl.view.ui.adapter.material.ConcreteParamsAdapter;
import com.sgb.kjwl.viewmodel.material.ConcreteDetailModel;
import com.stx.xhb.androidx.XBanner;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.DialogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

public class ConcreteDetailActivity extends AppActivity {

    private static MaterialFilterJson filterJson;
    private ActivityConcreteDetailBinding binding;
    @Inject
    ConcreteDetailModel model;
    private String id;
    private ConcreteDetailEntity data;
    private ConcreteAdmixAdapter admixAdapter;
    private ConcreteParamsAdapter strengthAdapter;
    private ConcreteParamsAdapter serviceAdapter;
    private ConcreteParamsAdapter gradtionAdapter;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMaterialComponent.builder().appComponent(appComponent).materialModule(new MaterialModule(this)).build().inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    public static void start(Context context, String id, MaterialFilterJson filterJson) {
        ConcreteDetailActivity.filterJson = filterJson;
        start(context, id);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setClass(context, ConcreteDetailActivity.class);
        context.startActivity(intent);
    }

    /**
     * 由购物车进入时需要带入订单号请求已选择的规格参数
     *
     * @param context
     * @param id
     * @param orderNo
     */
    public static void start(Context context, String id, String orderNo) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("orderNo", orderNo);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setClass(context, ConcreteDetailActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        id = getIntent().getStringExtra("id");
        binding = DataBindingUtil.setContentView(this, R.layout.activity_concrete_detail);
        binding.include.ivBack.setOnClickListener(this);
        binding.tvShop.setOnClickListener(this);
        binding.tvCall.setOnClickListener(this);
        binding.ivAdd.setOnClickListener(this);
        binding.ivMinus.setOnClickListener(this);
        binding.tvAddShoppingCar.setOnClickListener(this);
        binding.tvShoppingCar.setOnClickListener(this);
        binding.include.titleView.setText("商砼详情");

    }

    @Override
    protected void init() {
        if (filterJson == null) {
            model.getDetail(id);
        } else {
            model.getDetail(id, filterJson.getStrengthId(), filterJson.getGradationId(), filterJson.getServiceId());
        }
        model.getCarCount();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.tv_shop:
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), data.getProviderInfo().getProviderId(), "", 0, 0);
                break;
            case R.id.tv_call:
                DialogUtil.showTelDialog(this, "客服电话", "4000010051");
                break;
            case R.id.iv_add:
                int i = Integer.parseInt(binding.etNum.getText().toString());
                binding.etNum.setText(String.valueOf(i + 1));
                break;
            case R.id.iv_minus:
                int num = Integer.parseInt(binding.etNum.getText().toString());
                binding.etNum.setText(String.valueOf(num > 1 ? num - 1 : 1));
                break;
            case R.id.tv_add_shopping_car:
                model.checkToken("add_shopping_car");
                break;
            case R.id.tv_shopping_car:
                model.checkToken("shopping_car");
                break;
        }
    }

    public void showDetail(ConcreteDetailEntity data) {
        this.data = data;
        binding.setViewModel(data);
        ArrayList<CustomViewsInfo> imageListNo = new ArrayList<>();
        for (String entity : data.getImages()) {
            imageListNo.add(new CustomViewsInfo(entity));
        }
        binding.banner.setBannerData(imageListNo);
        //加载广告图片
        binding.banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                Glide.with(UiUtil.getContext()).load(imageListNo.get(position)).into((ImageView) view);
            }
        });

        strengthAdapter = showParams(binding.listStrength, data.getStrengthList());
        serviceAdapter = showParams(binding.listService, data.getServiceList());
        gradtionAdapter = showParams(binding.listGradtion, data.getGradationList());
        if (data.getAdmixtureList() != null) {
            showAdmixParam(binding.listAdmix, data.getAdmixtureList());
        }
        getPrice();
    }

    private void showAdmixParam(RecyclerView view, List<AdmixtureEntity> data) {
        view.setLayoutManager(new GridLayoutManager(this, 4));
        admixAdapter = new ConcreteAdmixAdapter(this, data);
        view.setAdapter(admixAdapter);
        admixAdapter.setOnItemClick(new AdapterOnItemClick<AdmixtureEntity>() {
            @Override
            public void onItemClick(AdmixtureEntity admixtureEntity, int position) {
                if (admixtureEntity.getSpec().size() == 2) {
                    if (admixAdapter.getSelect().get(position) == 0) {
                        admixAdapter.setSelect(position, 1);
                    } else {
                        admixAdapter.setSelect(position, 0);
                    }
                    admixAdapter.notifyDataSetChanged();
                    getPrice();
                } else {
                    showUnitPop(admixtureEntity, position);
                }
            }
        });
    }

    private ConcreteParamsAdapter showParams(RecyclerView view, List<ConcreteFilterEntity> data) {
        view.setLayoutManager(new GridLayoutManager(this, 4));
        ConcreteParamsAdapter adapter = new ConcreteParamsAdapter(this, data);
        view.setAdapter(adapter);
        adapter.setOnItemClick(new AdapterOnItemClick<ConcreteFilterEntity>() {
            @Override
            public void onItemClick(ConcreteFilterEntity concreteFilterEntity, int position) {
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
                getPrice();
            }
        });
        return adapter;
    }

    private void showUnitPop(AdmixtureEntity admixtureEntity, int position) {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                admixAdapter.setSelect(position, options1);
                admixAdapter.notifyDataSetChanged();
                getPrice();
            }
        }).setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();

        businessOption.setPicker(admixtureEntity.getSpec());
        businessOption.setTitleText(admixtureEntity.getAdmixtureName());
        businessOption.setSelectOptions(admixAdapter.getSelect().get(position));
        businessOption.show();
    }

    /**
     * 请求显示的价格（带筛选条件单价）
     * 强度等级：strongFactId
     * 外加剂：admixtureFactIds []
     * 服务：serviceId
     * 配置：gradationId
     * 商品id：no
     */
    private void getPrice() {
        ConcreteParamEntity concreteParamEntity = new ConcreteParamEntity();
        concreteParamEntity.setStrongFactId(strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getId());
        concreteParamEntity.setServiceId(serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getId());
        concreteParamEntity.setGradationId(gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getId());
        concreteParamEntity.setNo(data.getNo());

        HashMap<Integer, Integer> select = admixAdapter.getSelect();
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < select.size(); i++) {
            if (select.get(i) != 0) {
                strings.add(admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getId());
            }
        }
        concreteParamEntity.setAdmixtureFactIds(strings);
        model.getPrice(concreteParamEntity);
    }

    public void showPrice(String totalPrice) {
        binding.tvPrice.setText(totalPrice);
    }

    /**
     * 添加购物车时所需数据
     */
    public void addCart() {
        ConcreteParamEntity param = new ConcreteParamEntity();
        param.setItemId(data.getId());
        param.setProviderId(data.getProviderInfo().getProviderId());
        param.setStrongFactId(strengthAdapter.getDatas().get(strengthAdapter.getSelect()).getId());

        HashMap<Integer, Integer> select = admixAdapter.getSelect();
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 0; i < select.size(); i++) {
            if (select.get(i) != 0) {
                strings.add(admixAdapter.getDatas().get(i).getSpec().get(select.get(i)).getId());
            }
        }
        param.setAdmixtureFactIds(strings);
        param.setPumpPrice(serviceAdapter.getDatas().get(serviceAdapter.getSelect()).getPrice());
        param.setGradation1Price(gradtionAdapter.getDatas().get(gradtionAdapter.getSelect()).getPrice());
        param.setItemNum(binding.etNum.getText().toString());

        model.addCart(param);
    }

    public void refreshCarCount(String count) {
        if (Integer.parseInt(count) > 0) {
            binding.tvCarCount.setVisibility(View.VISIBLE);
            binding.tvCarCount.setText(count);
        } else {
            binding.tvCarCount.setVisibility(View.GONE);
        }
    }

    public void checkTokenView() {
        Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SHOPPING");
        MainActivity.start(ConcreteDetailActivity.this, intent);
    }
}